package com.cyj.dream.core.config.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * @Description: mybatis-plus自动填充器
 * @BelongsProject: DreamChardonnay
 * @BelongsPackage: com.cyj.dream.core.config.mybatisplus
 * @Author: ChenYongJia
 * @CreateTime: 2021-09-27 08:55
 * @Email: chen87647213@163.com
 * @Version: 1.0
 */
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 插入时的填充策略
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        boolean hasCreateTime = metaObject.hasSetter("createTime");
        boolean hasUpdateTime = metaObject.hasSetter("updateTime");

        if (hasCreateTime) {
            Object val = getFieldValByName("createTime", metaObject);
            if (val == null) {
                this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
            }
        }
        if (hasUpdateTime) {
            Object val = getFieldValByName("updateTime", metaObject);
            if (val == null) {
                this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
            }
        }
    }

    /**
     * 更新时的填充策略
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        boolean hasUpdateTime = metaObject.hasSetter("updateTime");
        if (hasUpdateTime) {
            Object val = getFieldValByName("updateTime", metaObject);
            //如果外部传入的实体设置了这个值就使用外部传入的值
            if (val == null) {
                this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
            }
        }
    }

}
